package inv.stask.logic;

import inv.stask.beans.Task;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class TaskUtil extends WriterUtil {
	public static final SimpleDateFormat sdf_yyyyMMdd	= new SimpleDateFormat("yyyyMMdd"); 
	
	protected MyProperties prop		= new MyProperties();
	protected String filename		= prop.getHomeDir() + File.separator + "tasks.ser";
	protected String filenameLock	= prop.getHomeDir() + File.separator + "tasks.ser.lock";
	
	@Override
	protected String getFilename() {
		return filename;
	}
	
	@Override
	protected String getLockFilename() {
		return filenameLock;
	}
	
	private void prepareIds(List<Task> tasks){
		int maxId	= 0;
		for(Task task: tasks){
			if(task.getId() != null)
				if(task.getId() > maxId)
					maxId = task.getId();
		}
		
		for(Task task: tasks){
			if(task.getId() == null)
				task.setId(++maxId);
		}
	}
	
	public void write(List<Task> tasks) {
		prepareIds(tasks);
		super.write(tasks);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Task> read() {
		return (List<Task>)super.read();
	}
	
	public static Date getToday() {
		return new Date();
	}
	
	public static boolean date_yyyyMMdd_equals(Date d1, Date d2){
		if(d1 == null && d2 == null)
			return true;
		
		if(d1 != null || d2 != null)
			return false;
		
		String s1 = sdf_yyyyMMdd.format(d1);
		String s2 = sdf_yyyyMMdd.format(d2);
		
		return s1.equals(s2);
	}
	
	
}
